<template>
	<view class="container">
		<!-- 顶部筛选栏 -->
		<view class="filter-bar">
			<view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'all' }"
				@click="selectFilter('all')"
			>
				<text class="filter-text">全部</text>
			</view>
			<view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'pending' }"
				@click="selectFilter('pending')"
			>
				<text class="filter-text">待审核</text>
				<view class="filter-badge" v-if="pendingCount > 0">
					<text class="badge-text">{{ pendingCount }}</text>
				</view>
			</view>
			<view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'completed' }"
				@click="selectFilter('completed')"
			>
				<text class="filter-text">已完成</text>
			</view>
			<view 
				class="filter-item" 
				:class="{ active: selectedFilter === 'rejected' }"
				@click="selectFilter('rejected')"
			>
				<text class="filter-text">已拒绝</text>
			</view>
		</view>
		
		<!-- 充值记录列表 -->
		<scroll-view 
			class="record-list" 
			scroll-y 
			@scrolltolower="loadMore"
			refresher-enabled
			@refresherrefresh="onRefresh"
			:refresher-triggered="refreshing"
		>
			<!-- 空状态 -->
			<view class="empty-container" v-if="!loading && records.length === 0">
				<text class="empty-text">暂无充值记录</text>
			</view>
			
			<view 
				class="record-card" 
				v-for="record in records" 
				:key="record.id"
				@click="goToDetail(record)"
			>
				<!-- 记录头部 -->
				<view class="record-header">
					<view class="record-info">
						<text class="record-time">{{ record.createDate }}</text>
						<text class="record-status" :class="getStatusClass(record.status)">{{ record.statusName }}</text>
					</view>
				</view>
				
				<!-- 记录内容 -->
				<view class="record-content">
					<view class="content-row">
						<text class="row-label">充值金额：</text>
						<text class="row-value amount">¥{{ record.amount }}</text>
					</view>
					<view class="content-row" v-if="record.userName">
						<text class="row-label">用户：</text>
						<text class="row-value">{{ record.userName }}</text>
					</view>
					<view class="content-row" v-if="record.shopName">
						<text class="row-label">店铺：</text>
						<text class="row-value">{{ record.shopName }}</text>
					</view>
					<view class="content-row" v-if="record.auditDate">
						<text class="row-label">审核时间：</text>
						<text class="row-value">{{ record.auditDate }}</text>
					</view>
					<view class="content-row" v-if="record.auditRemark">
						<text class="row-label">审核备注：</text>
						<text class="row-value">{{ record.auditRemark }}</text>
					</view>
				</view>
				
				<!-- 操作按钮 -->
				<view class="record-actions" v-if="record.status === '0' && type === '1'">
					<view class="action-btn reject-btn" @click.stop="handleReject(record)">
						<text class="btn-text">拒绝</text>
					</view>
					<view class="action-btn approve-btn" @click.stop="handleApprove(record)">
						<text class="btn-text">通过</text>
					</view>
				</view>
			</view>
			
			<!-- 加载更多提示 -->
			<view class="load-more" v-if="loading">
				<text class="load-text">加载中...</text>
			</view>
			<view class="load-more" v-if="!hasMore && records.length > 0">
				<text class="load-text">没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			type: '',
			title: '',
			selectedFilter: 'all', // 当前选中的筛选条件
			records: [], // 当前显示的记录列表
			allRecords: [], // 所有记录数据
			loading: false,
			refreshing: false,
			hasMore: true,
			pendingCount: 0, // 待审核数量
		}
	},
	onLoad(options) {
		if(options.type) {
			this.type = options.type
			if(this.type === '1') {
				this.selectedFilter = 'pending'
			}
		}
		if(options.title) {
			this.title = options.title
			uni.setNavigationBarTitle({
				title: this.title
			})
		}
		// 如果有筛选条件，使用传入的筛选条件
		if (options.filter) {
			this.selectedFilter = options.filter
		}
	},
	onShow() {
		// 页面显示时加载数据
		this.loadRecordList()
	},
	methods: {
		// 加载充值记录列表
		loadRecordList() {
			this.loading = true
			
			const params = {}
			
			// 根据筛选条件设置状态参数
			// if (this.selectedFilter === 'pending') {
			// 	params.status = '0'
			// } else if (this.selectedFilter === 'completed') {
			// 	params.status = '1'
			// } else if (this.selectedFilter === 'rejected') {
			// 	params.status = '2'
			// }
			params.type = this.type
			
			
			this.$u.api.wallet.rechargeList(params).then(res => {
				this.loading = false
				this.refreshing = false
				
				console.log('充值记录API响应:', res)
				
				// 兼容两种响应格式：result='true'
				if (res && (res.result == 'true')) {
					// 获取数据数组
					let dataList = res.data || res.list || []
					
					if (Array.isArray(dataList) && dataList.length > 0) {
						this.allRecords = dataList.map(item => ({
							id: item.id,
							userCode: item.userCode,
							userName: item.userName,
							shopCode: item.shopCode,
							shopName: item.shopName,
							amount: parseFloat(item.amount || 0).toFixed(2),
							status: String(item.status || '0'),
							statusName: item.statusName || '待审核',
							auditBy: item.auditBy || '',
							auditDate: item.auditDate || '',
							auditRemark: item.auditRemark || '',
							createDate: item.createDate || '',
							updateDate: item.updateDate || ''
						}))
						
						// 计算各状态数量
						this.pendingCount = this.allRecords.filter(r => r.status === '0').length
						
						// 根据当前筛选条件过滤记录
						this.filterRecords()
						
						console.log('处理后的记录数:', this.allRecords.length, '当前显示:', this.records.length)
					} else {
						this.allRecords = []
						this.records = []
						console.log('数据为空或格式不正确')
					}
				} else {
					this.allRecords = []
					this.records = []
					console.log('API响应格式不正确:', res)
				}
			}).catch(err => {
				this.loading = false
				this.refreshing = false
				console.error('加载充值记录失败:', err)
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				})
			})
		},
		
		// 根据筛选条件过滤记录
		filterRecords() {
			if (this.selectedFilter === 'all') {
				this.records = this.allRecords
			} else if (this.selectedFilter === 'pending') {
				this.records = this.allRecords.filter(r => r.status === '0')
			} else if (this.selectedFilter === 'completed') {
				this.records = this.allRecords.filter(r => r.status === '1')
			} else if (this.selectedFilter === 'rejected') {
				this.records = this.allRecords.filter(r => r.status === '2')
			}
		},
		
		// 选择筛选条件
		selectFilter(filter) {
			if (this.selectedFilter === filter) {
				return
			}
			this.selectedFilter = filter
			this.filterRecords()
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			if (status == '0') {
				return 'status-pending'
			} else if (status == '1') {
				return 'status-completed'
			} else if (status == '2') {
				return 'status-rejected'
			}
			return ''
		},
		
		// 跳转到详情页
		goToDetail(record) {
			if(this.type == '1' && record.status == '0') {
				uni.navigateTo({
					url: `/pages/inventoryManagement/recharge/recharge?recharge=${JSON.stringify(record)}&type=${this.type}&title=${this.title}`
				})
			}
		},
		
		// 处理审核通过
		handleApprove(record) {
			uni.showModal({
				title: '提示',
				content: '确定审核通过该充值申请吗？',
				success: (res) => {
					if (res.confirm) {
						this.auditRecord(record.id, '1')
					}
				}
			})
		},
		
		// 处理审核拒绝
		handleReject(record) {
			uni.showModal({
				title: '提示',
				content: '确定拒绝该充值申请吗？',
				success: (res) => {
					if (res.confirm) {
						this.auditRecord(record.id, '2')
					}
				}
			})
		},
		
		// 审核充值记录
		auditRecord(id, auditResult) {
			uni.showLoading({
				title: '审核中...',
				mask: true
			})
			
			this.$u.api.wallet.audit({
				id: id,
				auditResult: auditResult
			}).then(res => {
				uni.hideLoading()
				
				if (res && res.result == 'true') {
					uni.showToast({
						title: res.message || '审核成功',
						icon: 'success'
					})
					
					// 重新加载列表
					setTimeout(() => {
						this.loadRecordList()
					}, 1000)
				} else {
					uni.showToast({
						title: res.message || '审核失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('审核失败:', err)
				uni.showToast({
					title: '审核失败，请重试',
					icon: 'none'
				})
			})
		},
		
		// 下拉刷新
		onRefresh() {
			this.refreshing = true
			this.loadRecordList()
		},
		
		// 加载更多
		loadMore() {
			// 如果当前是筛选状态，不需要加载更多
			// 因为已经一次性加载了所有数据
			if (this.selectedFilter !== 'all') {
				return
			}
			
			// 这里可以根据实际需求实现分页加载
			// 目前API返回所有数据，所以不需要分页
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	min-height: calc(100vh - 50px);
	max-height: calc(100vh - 50px);
}

/* 筛选栏 */
.filter-bar {
	display: flex;
	background-color: #ffffff;
	padding: 10px 0;
	border-bottom: 1px solid #f0f0f0;
	position: sticky;
	top: 0;
	z-index: 10;
}

.filter-item {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 8px 0;
	position: relative;
}

.filter-item.active .filter-text {
	color: #ff4069;
	font-weight: bold;
}

.filter-text {
	font-size: 14px;
	color: #666666;
}

.filter-badge {
	position: absolute;
	top: 2px;
	right: 10px;
	background-color: #ff4069;
	border-radius: 10px;
	min-width: 18px;
	height: 18px;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 5px;
}

.badge-text {
	font-size: 10px;
	color: #ffffff;
}

/* 记录列表 */
.record-list {
	min-height: calc(100vh - 120px);
	max-height: calc(100vh - 120px);
	padding: 10px;
}

.empty-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100px 20px;
}

.empty-text {
	font-size: 14px;
	color: #999999;
}

/* 记录卡片 */
.record-card {
	background-color: #ffffff;
	border-radius: 8px;
	padding: 15px;
	margin-bottom: 10px;
}

.record-header {
	margin-bottom: 12px;
}

.record-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.record-time {
	font-size: 12px;
	color: #999999;
}

.record-status {
	font-size: 12px;
	padding: 4px 10px;
	border-radius: 12px;
}

.status-pending {
	background-color: #fff3cd;
	color: #856404;
}

.status-completed {
	background-color: #d4edda;
	color: #155724;
}

.status-rejected {
	background-color: #f8d7da;
	color: #721c24;
}

/* 记录内容 */
.record-content {
	margin-bottom: 12px;
}

.content-row {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
}

.content-row:last-child {
	margin-bottom: 0;
}

.row-label {
	font-size: 14px;
	color: #666666;
	min-width: 80px;
}

.row-value {
	font-size: 14px;
	color: #333333;
	flex: 1;
}

.row-value.amount {
	color: #ff4069;
	font-weight: bold;
	font-size: 16px;
}

/* 操作按钮 */
.record-actions {
	display: flex;
	gap: 10px;
	padding-top: 12px;
	border-top: 1px solid #f0f0f0;
}

.action-btn {
	flex: 1;
	height: 36px;
	border-radius: 18px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.approve-btn {
	background-color: #19be6b;
}

.reject-btn {
	background-color: #ff4069;
}

.btn-text {
	font-size: 14px;
	color: #ffffff;
	font-weight: bold;
}

/* 加载更多 */
.load-more {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 20px;
}

.load-text {
	font-size: 12px;
	color: #999999;
}
</style>

